import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
    constructor() { }

    // Immutability
    // Interceptors exist to examine and mutate outgoing requests and incoming responses. 
    // However, it may be surprising to learn that the HttpRequest and HttpResponse classes are largely immutable.
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // This is a duplicate. It is exactly the same as the original.
        // const dupReq = req.clone();

        // Change the URL and replace 'http://' with 'https://'
        // const secureReq = req.clone({ url: req.url.replace('http://', 'https://') });

        // Setting new headers
        // A common use of interceptors is to set default headers on outgoing responses. For example, 
        // assuming you have an injectable AuthenticationService which can provide an authentication token, 
        // here is how you would write an interceptor which adds it to all outgoing requests:
        // Get the auth header from the service.
        // const authHeader = this.auth.getAuthorizationHeader();

        // Clone the request to add the new header.
        // const authReq = req.clone({ headers: req.headers.set('Authorization', authHeader) });

        // The practice of cloning a request to set new headers is so common that there's actually a shortcut for it:
        // const authReq = req.clone({setHeaders: {Authorization: authHeader}});

        // Pass on the cloned request instead of the original request.
        // return next.handle(authReq);

        // An interceptor that alters headers can be used for a number of different operations, including:
        // - Authentication/authorization
        // - Caching behavior; for example, If-Modified-Since
        // - XSRF protection

        // const apiReq = req.clone({ url: `/dynamic${req.url}` });

        return next.handle(req);
    }
}